package com.lanyou.esb.cook.proxy.redis.persistent.base;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import redis.clients.jedis.exceptions.JedisException;

import com.lanyou.esb.cook.proxy.exception.PersistentDataException;
import com.lanyou.esb.cook.proxy.redis.persistent.StrtPersistentRedis;

/**
 * List数据类型，持久化REDIS数据基类
 * 
 * @author Davey.wu
 */
public abstract class StrBasePersistentRedis<T, K> extends
		BasePersistentRedis<T> implements StrtPersistentRedis<T, K> {

	@Override
	public void persistent() throws PersistentDataException, Exception {
		List<T> list = new ArrayList<>(this.getBatchAmount());
		list.clear();
		List<String> keys = null;
		List<T> objects = null;
		while (true) {
			try {
				keys = this.getKeysJedisProxy().lpopAsStr(
						this.getKeysJedisProxy().getKey(),
						this.getBatchReadSize());
				// 没有数据，返回
				if (keys == null || keys.isEmpty()) {
					break;
				}
				objects = this.getJedisProxy().get(keys);
				if (objects == null || objects.isEmpty()) {
					continue;
				}
				list.addAll(objects);
				// 达到批量保存的数目，将数据保存到数据库
				if (list.size() >= this.getBatchAmount()) {
					getService().save(list);
					list.clear();
					continue;
				}

			} catch (Exception e) {
				if (e instanceof JedisException) {
					e.printStackTrace();
					break;
				}
				// TODO 如果是将字符串转换成对象时出错，继续读后面的数据
				objects = null;
			}
		}
		// 保存剩余的数据
		getService().save(list);
		list.clear();
	}

}
